/*
 * RTFHandler.java
 *
 * Created on 4 September 2006, 3:17
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package fasea.index.filehandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Document;

/**
 *
 * @author gvasil
 */
class RTFHandler extends FileHandler {
    
    public Document getTypedDocument(File file) throws FileHandlerException {

      InputStream is = null;
      try {
          is = new FileInputStream(file);
      }
      catch (FileNotFoundException e) {
          throw new FileHandlerException(
                  "File not found: "
                  + file.getAbsolutePath(), e);
      }
      
      org.apache.lucene.document.Document doc = createDefaultLuceneDocument(file);
      
      String text = null;
      DefaultStyledDocument styledDoc = new DefaultStyledDocument();
      try {
          text = getText(is);
          /* Eat consecutive whitespace characters */
   //       text = text.replaceAll("\\s+", " ");
      }
      catch (IOException e) {
          throw new FileHandlerException(
                  "Cannot extract text from a RTF document", e);
      }
      catch (BadLocationException e) {
          throw new FileHandlerException(
                  "Cannot extract text from a RTF document", e);
      }
      
      if (text != null && (!text.equals(""))) {
          doc.add(new Field("content", text, Field.Store.NO,
                  Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
      }
      return doc;
    }
    
    private String getText(InputStream is) throws IOException, BadLocationException {
      String bodyText = null;
      DefaultStyledDocument styledDoc = new DefaultStyledDocument();
      
      new RTFEditorKit().read(is, styledDoc, 0);
      bodyText = styledDoc.getText(0, styledDoc.getLength());
      
      return bodyText;
    }
}
